package com.fastloan.common;

import com.fastloan.mgt.customer.service.ZyCustomerService;
import com.fastloan.safe.core.param.RoleTypeEnum;
import com.fastloan.safe.core.util.ManagerKit;
import com.fastloan.safe.mgt.org.service.CmuOrgService;
import com.fastloan.safe.mgt.org.service.CmuOrgUserService;
import com.fastloan.safe.mgt.user.service.CmuUserService;
import com.kawins.base.BaseMapper;
import com.kawins.base.BaseService;
import com.kawins.base.baseabs.BaseModel;
import com.kawins.base.baseabs.BaseServiceImpl;
import com.kawins.supers.file.IFileManager;
import com.kawins.supers.file.core.FileLoadBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.function.BiFunction;
import java.util.stream.Collectors;


/**
 * @author chenkai
 * createTime 2017-10-2017/10/16 20:33
 */
public class BasicServiceImpl<T extends BaseModel<?>> extends BaseServiceImpl<T> implements BaseService<T> {

    @Autowired
    private BaseMapper<T> baseDao;

    @Autowired
    protected IFileManager fileManager;

    @Autowired
    private CmuOrgService cmuOrgService;

    @Autowired
    private CmuUserService cmuUserService;

    @Autowired
    private ZyCustomerService zyCustomerService;

    @Autowired
    private CmuOrgUserService cmuOrgUserService;

    @Override
    protected BaseMapper<T> buildDao() {
        return baseDao;
    }

    /**
     * 上传文件转换并为对应Bean
     *
     * @param <V>      主键类型
     * @param <R>      返回类型
     * @param files    文件
     * @param function Bean的构造方法 参数一为对应主键 参数二为文件ID
     * @param pk       对应主体的主键
     * @return
     */
    protected <V, R> Map<FileLoadBean, R> upLoad(MultipartFile[] files, BiFunction<V, String, R> function, V pk) {
        if (files == null || Arrays.stream(files).anyMatch(multipartFile -> multipartFile.getSize() <= 0)) {
            return new HashMap<>();
        }
        List<FileLoadBean> upload = fileManager.upload(files);
        return upload.stream()
                .collect(Collectors.toMap(fileLoadBean -> fileLoadBean
                        , (FileLoadBean fileLoadBean) -> function.apply(pk, fileLoadBean.getFileId().toString())));
    }

    protected String getOrgIdByAdminOrOther() {
        String orgId = "";
        if (ManagerKit.getRole() != null && ManagerKit.getRole().getIndexType().equals(RoleTypeEnum.ADMIN.getCode())) {
            orgId = ManagerKit.getTopOrgId();
        } else if (ManagerKit.getOrgId() != null) {
            orgId = ManagerKit.getOrgId();
        }
        return orgId;
    }

}
